package Netty.old.NIO.群聊系统;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

public class 服务器 {
    private static final int PORT = 5438;
    private Selector selector;//选择器
    private ServerSocketChannel serverSocketChannel;//
    //构造前期
    public 服务器(){
        try {
            selector = Selector.open();//得到选择器
            serverSocketChannel = ServerSocketChannel.open();//获得ServerSocketChannel
            serverSocketChannel.socket().bind(new InetSocketAddress(PORT));//绑定端口
            serverSocketChannel.configureBlocking(false);//设置为非阻塞IO
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);//注册到selector选择器中
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        服务器 fwq = new 服务器();
        fwq.listen();
    }

    public void listen() {
        try {
            while (true) {
                if (selector.select(2000)>0){
                    Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
                    while (keys.hasNext()){
                        SelectionKey key = keys.next();
                        if(key.isAcceptable()){//监听到Accept
                            SocketChannel accept = serverSocketChannel.accept();//获取SocketChannel
                            accept.configureBlocking(false);//设置非阻塞
                            accept.register(selector,SelectionKey.OP_READ);//注册到selector选择器中
                            System.out.println(accept.getRemoteAddress() + "上线");
                            sendInfoToOther(accept.getRemoteAddress() + "上线",accept);
                        }
                        if (key.isReadable()) {//监听到READ
                            readData(key);//读取客户消息
                        }
                        keys.remove();//删除   防止重复操作
                    }
                }
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    private void readData(SelectionKey key){//读取客户消息
        SocketChannel channel = null;
        try {
            channel = (SocketChannel) key.channel();//获取SocketChannel
            ByteBuffer allocate = ByteBuffer.allocate(1024);
            if (channel.read(allocate)>0) {
                String msg = new String(allocate.array(),0,allocate.array().length);//转字符串
                System.out.println("from:" + msg.trim());
                sendInfoToOther(msg,channel);
            }
        }catch (IOException e){

            try {
                System.out.println(channel.getRemoteAddress() + "离线了");
                sendInfoToOther(channel.getRemoteAddress() + "离线了",channel);
                key.cancel();//取消注册
                channel.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }

        }
    }

    private void sendInfoToOther(String msg,SocketChannel channel) throws IOException {
//        System.out.println("转发消息中");
        for (SelectionKey key : selector.keys()){//取出所有注册的
            Channel c = key.channel();
            if(c instanceof SocketChannel && c != channel) {
                SocketChannel socketChannel = (SocketChannel) c;
                ByteBuffer wrap = ByteBuffer.wrap(msg.getBytes());
                socketChannel.write(wrap);
            }
        }
    }
}
